import http from '../utils/http'

const TOKEN = 'App-Token'
const USER_INFO = 'userInfo'


//检查手机号认证
function checkAuth() {
  return new Promise((resolve, reject) => {
    const user = wx.getStorageSync(USER_INFO)
    if (user.phone == '' || user.phone == null || user.phone == undefined) {
      resolve(false)
    }
    resolve(true)
  })
}


/**
 * 登录
 */
function login() {
  return new Promise((resolve, reject) => {
    wx.login({
      success: (res) => {
        const data = {
          code: res.code
        }
        http.post('/login', data).then(res => {
          if (res.code == 200) {
            const loginInfo = res.data
            wx.setStorageSync(TOKEN, loginInfo.token)
            wx.setStorageSync(USER_INFO, loginInfo.userInfo)
            resolve(res)
          } else {
            wx.showToast({
              title: '登录失败，请重新进入小程序',
              icon: 'none', // 可选值：success, loading, none
              duration: 1500, // 提示显示时间，单位为毫秒，默认值为1500
              mask: false // 是否显示透明蒙层，防止触摸穿透，默认为false
            })
            reject(res)
          }
        })
      },
    })
  })
}
/**
 * 获取登录用户信息（异步函数）
 */
async function getUser() {
  let user = wx.getStorageSync(USER_INFO);
  if (!user) {
    try {
      user = await getInfo(); // 调用异步获取用户信息的函数
    } catch (error) {
      console.error('Failed to get user information:', error);
    }
  }
  return user;
}

/**
 * 获取用户信息
 */
function getInfo() {
  return new Promise((resolve, reject) => {
    http.get('/getInfo').then(res => {
      if (res.code == 200) {
        wx.setStorageSync(USER_INFO, res.data);
        resolve(res.data);
      } else {
        reject(res.msg); // 在请求失败时reject错误
      }
    }).catch(error => {
      reject(error); // 捕获http.get内部可能抛出的错误并reject
    });
  });
}

function logout() {
  wx.removeStorageSync(TOKEN)
  wx.removeStorageSync(USER_INFO)
}

exports.login = login
exports.logout = logout
exports.getInfo = getInfo
exports.getUser = getUser
exports.checkAuth = checkAuth
exports.TOKEN = TOKEN
exports.USER_INFO = USER_INFO